package com.bw.kylin1705f.web;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.bw.kylin1705f.dto.UserDto;
import com.bw.kylin1705f.entity.User;
import com.bw.kylin1705f.service.IUserService;
import com.bw.kylin1705f.vo.ResultEntity;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Mht
 * @since 2019-12-05
 */
@RestController
@RequestMapping("/user")
@CrossOrigin(origins="*",allowCredentials = "true")
public class UserController {

    @Autowired
    IUserService userService;


    @Autowired
    PasswordEncoder encoder;

    @Value("${user.img.path}")
    String useImgPath;
    @Value("${user.img.url}")
    String userImgUrl;

    @RequestMapping(value = "/userList",method = RequestMethod.GET)
    public ResultEntity getUserList(UserDto userDto){
//        Wrapper<User> wrapper = new EntityWrapper<User>();
//        if (StringUtils.isNotEmpty(userDto.getUsername())){
//            wrapper.like("username",userDto.getUsername());
//        }
//        Page<User> page = new Page(userDto.getPageNo(),userDto.getPageSize());

        PageHelper.startPage(userDto.getPageNo(),userDto.getPageSize());
        User user = new User();
        BeanUtils.copyProperties(userDto,user);
        List<User> userListByParam = this.userService.getUserListByParam(user);
        PageInfo<User> pageInfo = new PageInfo<User>(userListByParam);

        //Page<User> users = userService.selectPage(page,wrapper);
        return ResultEntity.ok(pageInfo);
    }


    @RequestMapping(method = RequestMethod.POST)
    public ResultEntity add(@ModelAttribute UserDto userDto) throws IOException {

        String originalFilename = "";
        String suffixName = "";
        String fileName = "";
        for (MultipartFile multipartFile : userDto.getFiles()) {
            //获取名字
            originalFilename = multipartFile.getOriginalFilename();
             suffixName  = originalFilename.substring(originalFilename.lastIndexOf("."));
             //重新生成的图片名称
             fileName = UUID.randomUUID().toString().concat(suffixName);
             File file = new File(useImgPath.concat(fileName));
             if (!file.getParentFile().exists()){
                 file.getParentFile().mkdirs();
             }
            multipartFile.transferTo(file);
        }


        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("username",userDto.getUsername());
        User user1 = userService.selectOne(wrapper);
        if (user1!=null){
           return ResultEntity.error("用户名已经存在");
        }

        User user = new User();
        BeanUtils.copyProperties(userDto,user);
        user.setPassword(encoder.encode("123456"));
        user.setProvince(userDto.getValue()[0]);
        user.setCity(userDto.getValue()[1]);
        user.setDistrict(userDto.getValue()[2]);
        user.setUserface(userImgUrl.concat(fileName));
        userService.insert(user);
        return ResultEntity.ok();
    }

    @RequestMapping(method = RequestMethod.PUT)
    public ResultEntity update(@ModelAttribute UserDto userDto) throws IOException {

        String originalFilename = "";
        String suffixName = "";
        String fileName = "";
        if (userDto.getFiles()!=null){
            for (MultipartFile multipartFile : userDto.getFiles()) {
                //获取名字
                originalFilename = multipartFile.getOriginalFilename();
                suffixName  = originalFilename.substring(originalFilename.lastIndexOf("."));
                //重新生成的图片名称
                fileName = UUID.randomUUID().toString().concat(suffixName);
                File file = new File(useImgPath.concat(fileName));
                if (!file.getParentFile().exists()){
                    file.getParentFile().mkdirs();
                }
                multipartFile.transferTo(file);
            }
        }


        User user = new User();
        BeanUtils.copyProperties(userDto,user);
        user.setPassword(encoder.encode("123456"));
        user.setProvince(userDto.getValue()[0]);
        user.setCity(userDto.getValue()[1]);
        user.setDistrict(userDto.getValue()[2]);
        if (userDto.getImages()!=null){
            user.setUserface(userDto.getImages()[0]);
        }
        if (StringUtils.isNotEmpty(fileName)){
            user.setUserface(userImgUrl.concat(fileName));
        }
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("id",user.getId());
        userService.update(user,wrapper);
        return ResultEntity.ok();
    }
}
